var winston = require('winston');
var mysql = require('mysql');
var utils = require('../lib/utils');

module.exports = function(pool, req, res, next){
	var eventId = req.params.eventId;
	var shareContent = req.body.shareContent;
	if(!shareContent){
		res.status(400).send('missing parameter, shareContent is required!')
		return
	}
	var queryString = "SELECT uri_map FROM share_list where share_content='" + shareContent + "'";
	
	pool.getConnection(function(err, connection){
		if(err){
			winston.error('DB connection error: ' + err);
			res.status(500).send('DB connection error: ' + err);
		}
		connection.query(queryString, function(err, rows){
			if(err){
				winston.error('DB query error: ' + err);
				res.status(500).send('DB query error: ' + err);
			}else{
				if(rows.length > 0){
					res.send(rows[0]);
				}else{
					var uriMap = utils.generateName(10);
					var queryString = 'INSERT INTO share_list (share_content, uri_map, timestamp, event_id) VALUES (?, ?, ?, ?)';
					var params = [shareContent, uriMap, String.from(Date.now()), eventId];
					queryString = mysql.format(queryString, params);
					connection.query(queryString, function(err){
						if(err){
							winston.error('DB query error: ' + err);
							res.status(500).send('DB query error: ' + err);
							connection.release();
						}else{
							res.send({'uri_map': uriMap});
						}
					});
				}
			}
			connection.release();
		});
	});

}